package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.twu.biblioteca.domain.LibraryItem;
import com.twu.biblioteca.domain.User;

/**
 * Created by mnewman on 30/07/2014.
 */
public class LibraryItemManager<T extends LibraryItem> {
    private final List<T> available;
    private final List<T> checkedOut;
    private final HashMap<T, User> holders;

    public LibraryItemManager(List<T> initialItems) {
        this.available = new ArrayList<>(initialItems);
        this.checkedOut = new ArrayList<>();
        this.holders = new HashMap<>();
    }

    public List<T> getAvailable() {
        return available;
    }

    public boolean checkout(String title, User user) {

        for (int i = 0 ; i < available.size(); i++) {
            if (available.get(i).getID().equals(title)) {
                checkedOut.add(available.get(i));
                holders.put(available.get(i), user);
                available.remove(i);

                return true;
            }
        }

        return false;
    }

    public boolean returnItem(String title, User user) {
        Integer index = getIndexByTitle(checkedOut, title);

        if (index != null) {
            User u = holders.get(checkedOut.get(index));
            if (u.equals(user)) {
                available.add(checkedOut.get(index));
                checkedOut.remove(index);
                holders.remove(u);
                return true;
            }
        }

        return false;

    }

    private Integer getIndexByTitle(List<T> list, String title) {

        for (int i = 0 ; i < list.size(); i++) {
            if (list.get(i).getID().equals(title)) {
                return i;
            }
        }

        return null;
    }

    public User getCheckoutInfo(String title) {
        Integer index = getIndexByTitle(checkedOut, title);

        if (index != null) {
            User u = holders.get(checkedOut.get(index));
            return u;
        }

        return null;
    }
}
